#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据初始化扩展脚本
用于强制初始化根目录和基础数据结构
"""

import os
import sys
import logging
from datetime import datetime

# 添加项目根目录到路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

from src.common.database import get_session, init_global_session
from src.models.file import VirtualFile
from src.models.base import ROOT_DIRECTORY_ID
from src.models.storage import VirtualStorage
from src.models.cloud import CloudAccount
from src.models.user import WebDAVUser
from src.utils.config import get_cloud_config, get_database_url

class DataInitializer:
    """数据初始化器"""
    
    def __init__(self):
        pass
        
    def force_init_root_directory(self):
        """强制初始化根目录"""
        print("🔧 强制初始化根目录...")
        
        with get_session() as session:
            try:
                # 检查根目录是否存在
                root_dir = session.query(VirtualFile).filter_by(
                    id=ROOT_DIRECTORY_ID,
                    is_directory=True
                ).first()
                
                if not root_dir:
                    # 创建根目录
                    root_dir = VirtualFile(
                        id=ROOT_DIRECTORY_ID,
                        name='',
                        path='/',
                        parent_id=None,
                        is_directory=True,
                        file_size=0
                    )
                    session.add(root_dir)
                    session.commit()
                    print("✅ 根目录强制初始化完成")
                else:
                    print("✅ 根目录已存在")
                return True
            except Exception as e:
                session.rollback()
                print(f"❌ 根目录初始化失败: {e}")
                return False
    
    def init_default_users(self):
        """初始化默认用户"""
        print("👤 初始化默认用户...")
        
        with get_session() as session:
            # 检查是否已存在默认WebDAV用户
            admin_user = session.query(WebDAVUser).filter_by(username='admin').first()
            if not admin_user:
                admin_user = WebDAVUser(
                    username='admin',
                    password_hash=WebDAVUser.hash_password('admin123'),
                    root_path='/',
                    can_read=True,
                    can_write=True,
                    can_delete=True
                )
                session.add(admin_user)
                print("✅ 创建默认管理员用户: admin/admin123")
            else:
                print("✅ 默认管理员用户已存在")
            
            session.commit()
    
    def init_default_cloud_accounts(self):
        """初始化默认云盘账号"""
        print("☁️ 初始化默认云盘账号...")
        
        tianyi_config = get_cloud_config('tianyi')
        
        with get_session() as session:
            # 检查是否已存在默认天翼云盘账号
            tianyi_account = session.query(CloudAccount).filter_by(
                cloud_provider='tianyi',
                cloud_account=tianyi_config['default_account']
            ).first()
            
            if not tianyi_account:
                tianyi_account = CloudAccount(
                    cloud_provider='tianyi',
                    cloud_account=tianyi_config['default_account'],
                    cloud_password=tianyi_config['default_password'],
                    display_name=tianyi_config['display_name'],
                    is_active=True
                )
                session.add(tianyi_account)
                print(f"✅ 创建默认天翼云盘账号: {tianyi_config['default_account']}")
            else:
                print("✅ 默认天翼云盘账号已存在")
            
            session.commit()
    
    def create_sample_directories(self):
        """创建示例目录结构"""
        print("📁 创建示例目录结构...")
        
        sample_dirs = [
            "Documents",
            "Pictures", 
            "Videos",
            "Music",
            "Downloads",
            "Backup"
        ]
        
        with get_session() as session:
            for dir_name in sample_dirs:
                # 检查目录是否已存在
                existing_dir = session.query(VirtualFile).filter_by(
                    name=dir_name,
                    parent_id=ROOT_DIRECTORY_ID,
                    is_folder=True
                ).first()
                
                if not existing_dir:
                    new_dir = VirtualFile(
                        name=dir_name,
                        parent_id=ROOT_DIRECTORY_ID,
                        is_folder=True,
                        owner_id=1,
                        created_at=datetime.utcnow(),
                        updated_at=datetime.utcnow()
                    )
                    session.add(new_dir)
                    print(f"✅ 创建目录: {dir_name}")
                else:
                    print(f"✅ 目录已存在: {dir_name}")
            
            session.commit()
    
    def full_initialization(self):
        """完整初始化"""
        print("="*60)
        print("🚀 WebDAV数据完整初始化")
        print("="*60)
        
        success = True
        
        # 1. 强制初始化根目录
        if not self.force_init_root_directory():
            success = False
        
        # 2. 初始化默认用户
        try:
            self.init_default_users()
        except Exception as e:
            print(f"❌ 用户初始化失败: {e}")
            success = False
        
        # 3. 初始化默认云盘账号
        try:
            self.init_default_cloud_accounts()
        except Exception as e:
            print(f"❌ 云盘账号初始化失败: {e}")
            success = False
        
        # 4. 创建示例目录
        try:
            self.create_sample_directories()
        except Exception as e:
            print(f"❌ 示例目录创建失败: {e}")
            success = False
        
        print("="*60)
        if success:
            print("✅ 数据初始化完成！")
        else:
            print("❌ 数据初始化过程中出现错误")
        print("="*60)
        
        return success

def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description='WebDAV数据初始化工具')
    parser.add_argument('--root-only', action='store_true', help='仅初始化根目录')
    parser.add_argument('--users-only', action='store_true', help='仅初始化用户')
    parser.add_argument('--accounts-only', action='store_true', help='仅初始化云盘账号')
    parser.add_argument('--dirs-only', action='store_true', help='仅创建示例目录')
    parser.add_argument('--full', action='store_true', help='完整初始化（默认）')
    
    args = parser.parse_args()
    
    initializer = DataInitializer()
    
    if args.root_only:
        initializer.force_init_root_directory()
    elif args.users_only:
        initializer.init_default_users()
    elif args.accounts_only:
        initializer.init_default_cloud_accounts()
    elif args.dirs_only:
        initializer.create_sample_directories()
    else:
        # 默认执行完整初始化
        initializer.full_initialization()

if __name__ == '__main__':
    main()
